package game.logic.app;

import com.google.common.collect.ArrayListMultimap;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public final class Solutions
{
    private static final ArrayListMultimap<String, String> solutionMaps = ArrayListMultimap.create();
    private static final List<String> ids = new ArrayList<>();
    private static final Random random = new Random();

    public static void load(File file)
    {
        solutionMaps.clear();
        ids.clear();
        try
        {
            Files.lines(file.toPath())
                .forEach(line -> {
                    String[] kv = line.split(",");
                    solutionMaps.put(kv[0], kv[1]);
                    ids.add(kv[0]);
                });
        } catch (IOException ignored)
        {}
    }

    public static String find(String id)
    {
        List<String> solutions = solutionMaps.get(id);
        return solutions.isEmpty() ? null : solutions.getFirst();
    }

    public static String randomPuzzle()
    {
        if (solutionMaps.isEmpty())
            return null;

        int idx = random.nextInt(solutionMaps.size());
        return ids.get(idx);
    }
}
